﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ProjectScheduling_web.dao;
using ProjectScheduling_web.model;
using ProjectScheduling_web.pagemodel;

namespace ProjectScheduling_web.Controllers.U
{
    [ApiController]
    public class MemberController : BController
    {
        private static readonly MemberDao @base = MemberDao.Base;
        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(LoginModel req)
        {
            if (string.IsNullOrEmpty(req.Name = req.Name?.ToString() ?? "") || string.IsNullOrEmpty(req.Pass = req.Pass?.Trim() ?? ""))
                return Fail("登录名和密码不能为空");
            req.Pass = Common.Md5(req.Pass);
            var obj = @base.Find(it => !string.IsNullOrEmpty(it.Name) && !string.IsNullOrEmpty(it.Password) && it.Name.Equals(req.Name) && it.Password.Equals(req.Pass));
            if (obj == null)
            {
                return Fail("登录名或者密码有误");
            }
            else
            {
                if (obj.IsLock)
                    return Fail("当前用户已锁定，请联系管理员");
                obj.Token = Guid.NewGuid().ToString().Replace("-", "");
                @base.Update(obj, it => new { it.Token });
                return Ok(new { state = true, msg = obj.Token, admin = obj.IsAdmin });
            }
        }
        [HttpGet]
        public ActionResult GetInfo()
        {
            if (CurrUser==null) return Fail("获取登录状态有误");
            return Success(new
            {
                CurrUser.Name,
                CurrUser.TrueName,
                CurrUser.Sex,
                CurrUser.Phone
            });
        }
        [HttpPost]
        public ActionResult Updatepwd(UpdatepwdModel req)
        {
            if (req == null) return Fail("当前请求错误");
            if (CurrUser==null) return Fail("获取登录状态有误");
            if (string.IsNullOrEmpty(req.oldpass = req.oldpass?.Trim())) return Fail("当前密码不能为空");
            if (string.IsNullOrEmpty(req.newpass = req.newpass?.Trim())) return Fail("新密码不能为空");
            if (Common.Md5(req.oldpass) != CurrUser.Password) return Fail("当前密码不正确");
            CurrUser.Password = Common.Md5(req.newpass);
            @base.Update(CurrUser, it => new { it.Password });
            return Success("修改成功");
        }
        [HttpGet]
        public ActionResult Names()
        {
            return Success(@base.AllNames());
        }
    }
}
